import subprocess


class _CustomAnchorCmdItem:
    def __init__(self):
        self.__enabled = False
        self.__cmd = ""

    def serialize(self):
        return (self.enabled, self.cmd)

    def deserialize(self, data):
        if data:
            self.enabled = data[0]
            self.cmd = data[1]

    @property
    def enabled(self):
        return self.__enabled

    @enabled.setter
    def enabled(self, state):
        self.__enabled = state

    @property
    def cmd(self):
        return self.__cmd

    @cmd.setter
    def cmd(self, cmd):
        self.__cmd = cmd


class AnchorCMD:
    http = _CustomAnchorCmdItem()
    ftp = _CustomAnchorCmdItem()
    magnet = _CustomAnchorCmdItem()

    @staticmethod
    def dict():
        return {
            'http': AnchorCMD.http,
            'https': AnchorCMD.http,
            'ftp': AnchorCMD.ftp,
            'magnet': AnchorCMD.magnet
        }

    @staticmethod
    def serialize():
        return {
            'http': AnchorCMD.http.serialize(),
            'ftp': AnchorCMD.ftp.serialize(),
            'magnet': AnchorCMD.magnet.serialize()
        }

    @staticmethod
    def deserialize(data):
        if not data:
            return
        AnchorCMD.http.deserialize(data['http'])
        AnchorCMD.ftp.deserialize(data['ftp'])
        AnchorCMD.magnet.deserialize(data['magnet'])

    #@staticmethod
    #def serializeDefault():
    #    return {}

    @staticmethod
    def handle(scheme, url):
        cmds = AnchorCMD.dict()
        if scheme in cmds and cmds[scheme].enabled:
            cmdSplit = cmds[scheme].cmd.split(" ")
            cmdSplit = [c.replace("%url", url) for c in cmdSplit]
            subprocess.run(cmdSplit) 
            return True
        return False
